package account;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.sql.*;

public class AccountCreate extends HttpServlet
{
	Connection conn;

	 public Boolean createAccount(String usuario, String password){ 
			try
			{  
		          Class.forName("org.postgresql.Driver").newInstance();  
		    }
			catch (Exception e)
			{  
		    }  
			try {
				conn = DriverManager.getConnection("jdbc:postgresql://localhost/mc436","root","G6sAK8ea"); 
			} catch (SQLException e) {
				System.err.println("Nao foi possivel obter conexao com banco!");
				e.printStackTrace();
			}   
			try{
				 Statement st0 = conn.createStatement();
		         ResultSet rs = st0.executeQuery("SELECT login FROM usuarios");
		         while (rs.next()) {
		             if(rs.getString("login").equals(usuario))
		             {
		            	return false;
		             }
		         }
			
	         PreparedStatement st = conn.prepareStatement("INSERT INTO usuarios VALUES('"+usuario+"','"+password+"')" );
	         st.executeUpdate();
	         	
	         
	         st.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
			return true;
	}
	 
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException 
	{
		this.doGet(request, response);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException 
	{
		String usuario = String.valueOf(request.getParameter("usuario"));
		String pass = String.valueOf(request.getParameter("password"));
		
		if(createAccount(usuario, pass))
		{
			request.getSession().setAttribute("password", pass);
			request.getSession().setAttribute("userName", usuario);
			request.getSession().setAttribute("loginState", "logged");
			request.setAttribute("cadastroStatus", "Sucesso");
			
			RequestDispatcher rdIndex = request.getRequestDispatcher("index.jsp");
			rdIndex.forward(request, response);
		}
		else
		{
			
			request.setAttribute("cadastroStatus", "Erro");
			RequestDispatcher rdIndex = request.getRequestDispatcher("index.jsp");
			rdIndex.forward(request, response);
		}
			
		
				
	}
}
	
	
 